<template>
  <div>
    <h1>拖拽限制：只能是三级，分为两种类型->前后，内 （判断）</h1>
    <h1>同步数据库：数据的集合->前后，内 （判断）</h1>

    <el-switch v-model="draggable"
               inactive-text="拖拽开关：">
    </el-switch>
    <el-tree :data="data"
             :props="defaultProps"
             :expand-on-click-node="false"
             node-key="catId"
             :draggable="draggable"
             :default-expanded-keys="defaultExpandedKeys"
             :allow-drop="allowDrop"
             @node-drop="nodeDrop">
      <span class="custom-tree-node"
            slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.data.catLevel != 3"
                     type="text"
                     size="mini"
                     @click="() => append(node,data)">
            Append
          </el-button>
          <el-button type="text"
                     size="mini"
                     @click="() => Update(node,data)">
            Update
          </el-button>
          <el-button type="text"
                     size="mini"
                     @click="() => remove(node,data)"
                     v-if="data.categoryEntities == undefined ">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <!-- 保存操作 -->
    <el-dialog title="分类"
               :visible.sync="dialogFormVisible">
      {{ category }}<br />
      <el-form :model="category">
        <el-form-item label="分类名称"
                      label-width="120px">
          <el-input v-model="category.name"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      updTree: [],
      level: 0,
      draggable: false,
      defaultExpandedKeys: [],
      url: 'save',
      data: [],
      defaultProps: {
        children: 'categoryEntities',
        label: 'name'
      },
      category: {
        catId: '',
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0
      },
      dialogFormVisible: false
    }
  },
  created () {
    this.getTreeList()
  },
  methods: {
    getTreeList () {
      this.$http({
        url: this.$http.adornUrl('/product/category/treeList', false),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        this.data = data.page
      })
    },
    append (node, data) {
      console.log(node, data)
      this.category = {
        catId: 0,
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0
      }
      this.category.parentCid = node.data.catId
      this.category.catLevel = node.data.catLevel + 1
      this.dialogFormVisible = true
    },
    save () {
      this.dialogFormVisible = false
      console.log(this.category.catId.length)
      if (this.category.catId > 0) {
        this.url = 'update'
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/${this.url}`, false),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        console.log(data)
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.defaultExpandedKeys.push(this.category.parentCid)
        this.getTreeList()
      })
    },
    Update (node, data) {
      console.log(node, data)
      this.dialogFormVisible = true
      this.$http({
        url: this.$http.adornUrl(
          `/product/category/info/${node.data.catId}`,
          false
        ),
        method: 'get'
      }).then(({ data }) => {
        this.category.catId = data.category.catId
        this.category.name = data.category.name
        this.category.parentCid = data.category.parentCid
        this.category.catLevel = data.category.catLevel
        this.category.showStatus = data.category.showStatus
        this.category.sort = data.category.sort
      })
    },
    remove (node, data) {
      console.log(node, data)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`, false),
            method: 'post',
            params: this.$http.adornParams({ id: node.data.catId }, false)
          }).then(({ data }) => {
            console.log(data)
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getTreeList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /**
     * 拖拽规则
     * 先查一遍被拖拽目标的层级进行比较
     * 前后类型：
     * 如果有1层 直接放行
     * 如果有两层并且目标的层级不能为三 放行
     * 如果有三层并且目标层级是1 放行
     * inner类型：
     * 如果有一层并且目标层级不能为三 放行
     * 如果有两层并且目标为为1 放行
     * 如果有三层 无
     */
    allowDrop (draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      this.level = 1
      this.getLevel(draggingNode.childNodes)
      // console.log(this.level)
      if (type === 'prev' || type === 'next') {
        if (this.level === 1) return true
        if (this.level === 2 && dropNode.data.catLevel !== 3) return true
        if (this.level === 3 && dropNode.data.catLevel === 1) return true
      } else if (type === 'inner') {
        if (this.level === 1 && dropNode.data.catLevel !== 3) return true
        if (this.level === 2 && dropNode.data.catLevel === 1) return true
      }
      return false
    },
    getLevel (childNodes) {
      if (childNodes.length !== 0) {
        this.level = 2
        for (var i in childNodes) {
          if (childNodes[i].childNodes.length !== 0) {
            this.level = 3
          }
        }
      }
    },
    /**
     * 拖拽成功后处理结果集返回后台进行同步
     * 两种情况： 处理的参数->parentId carLevel sort
     按分层（
     * 前后：
     * 如果有一层->
     * 1.如果与目标对象同级 parentId=目标对象pid carLevel不变 sort 获取目标对象的父类的子集排序
     * 2.如果目标对象level为2或1 parentId=目标对象的pid level =目标层级 排序 目标对象父类的子集
     * 如果有两层->
     * 1.如果被拖拽目标与拖拽目标同级 level不变 被拖拽目标的parentId=拖拽目标的parentId  拿到目标对象父类的子类 dropNode.parent.categoryEntities
     * 2.如果被拖拽目标与拖拽目标不同级 level=目标对象的level 子集遍历level-1 parentId=目标对象的pid  dropNode.parent.data 进行排序
     * 如果有三层->返回集合 pid不变 level不变 updTree=dropNode.parent.data（重新定义对象放进去） 遍历 加上sort=下标
     * inner：
     * 不论）
     * 按属性：
     */
    nodeDrop (draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      this.level = 1
      this.getLevel(draggingNode.childNodes)
      if (type === 'after' || type === 'before') {
        console.log(dropNode)
        this.getAfOrBe(dropNode)
        if (this.level === 2) {
          this.getTwoTree(draggingNode, dropNode)
        }
        // if (draggingNode.data.categoryEntities.length > 0 && dropNode.data.catLevel === 1) {
        //   this.getTwoTree(draggingNode)
        // }
      } else if (type === 'inner') {
        // console.log(dropNode)
        for (let index = 0; index < dropNode.data.categoryEntities.length; index++) {
          this.updTree.push({
            catId: dropNode.data.categoryEntities[index].catId,
            name: dropNode.data.categoryEntities[index].name,
            parentCid: dropNode.data.catId,
            catLevel: dropNode.data.catLevel + 1,
            sort: index
          })
          console.log(dropNode.data.categoryEntities[index].catId, dropNode.data.categoryEntities[index].name
            , dropNode.data.catId, dropNode.data.catLevel + 1)
        }
        if (this.level === 2) {
          this.getTwoTree(draggingNode, dropNode, 2)
        }
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/updates`, false),
        method: 'post',
        data: this.$http.adornData(this.updTree, false)
      }).then(({ data }) => {
        console.log(data)
        this.defaultExpandedKeys = []
        this.defaultExpandedKeys.push(dropNode.data.parentCid)
        this.updTree = []
        this.$message({
          message: '拖拽成功',
          type: 'success'
        })
        this.getTreeList()
      })
    },
    getAfOrBe (dropNode) {
      if (dropNode.data.catLevel === 1) {
        for (let index = 0; index < dropNode.parent.data.length; index++) {
          this.updTree.push({
            catId: dropNode.parent.data[index].catId,
            name: dropNode.parent.data[index].name,
            parentCid: dropNode.data.parentCid,
            catLevel: dropNode.data.catLevel,
            sort: index
          })
          console.log('一级', dropNode.parent.data[index].catId, dropNode.parent.data[index].name, dropNode.data.parentCid, dropNode.data.catLevel)
        }
      } else {
        for (let index = 0; index < dropNode.parent.data.categoryEntities.length; index++) {
          this.updTree.push({
            catId: dropNode.parent.data.categoryEntities[index].catId,
            name: dropNode.parent.data.categoryEntities[index].name,
            parentCid: dropNode.data.parentCid,
            catLevel: dropNode.parent.data.catLevel + 1,
            sort: index
          })
          console.log('多级', dropNode.parent.data.categoryEntities[index].catId, dropNode.parent.data.categoryEntities[index].name, dropNode.data.parentCid, dropNode.parent.data.catLevel + 1)
        }
      }
    },
    getTwoTree (draggingNode, dropNode, level = 1) {
      for (let index = 0; index < draggingNode.data.categoryEntities.length; index++) {
        this.updTree.push({
          catId: draggingNode.data.categoryEntities[index].catId,
          name: draggingNode.data.categoryEntities[index].name,
          parentCid: draggingNode.data.categoryEntities[index].parentCid,
          catLevel: dropNode.data.catLevel + level,
          sort: index
        })
        console.log('第二层', draggingNode.data.categoryEntities[index].catId, draggingNode.data.categoryEntities[index].name, draggingNode.data.categoryEntities[index].parentCid, dropNode.data.catLevel + level)
      }
    }
  }
}
</script>
nodeDrop:按层级的逻辑
 // if (this.level === 3) {
        //   for (let index = 0; index < dropNode.parent.data.length; index++) {
        //     this.updTree.push({
        //       catId: dropNode.parent.data[index].catId,
        //       name: dropNode.parent.data[index].name,
        //       parentCid: dropNode.parent.data[index].parentCid,
        //       catLevel: dropNode.parent.data[index].catLevel,
        //       sort: index
        //     })
        //   }
        //   console.log('收到的集合', this.updTree)
        // } else if (this.level === 2) {
        //   if (dropNode.data.catLevel === 2) {
        //     for (let index = 0; index < dropNode.parent.data.categoryEntities.length; index++) {
        //       this.updTree.push({
        //         catId: dropNode.parent.data.categoryEntities[index].catId,
        //         name: dropNode.parent.data.categoryEntities[index].name,
        //         parentCid: dropNode.data.parentCid,
        //         catLevel: dropNode.parent.data.categoryEntities[index].catLevel,
        //         sort: index
        //       })
        //     }
        //     console.log('收到的集合', this.updTree)
        //   }
        //   if (dropNode.data.catLevel === 1) {
        //     for (let index = 0; index < dropNode.parent.data.length; index++) {
        //       this.updTree.push({
        //         catId: dropNode.parent.data[index].catId,
        //         name: dropNode.parent.data[index].name,
        //         parentCid: dropNode.data.parentCid,
        //         catLevel: dropNode.data.catLevel,
        //         sort: index
        //       })
        //     }
        //     for (let index = 0; index < draggingNode.data.categoryEntities.length; index++) {
        //       this.updTree.push({
        //         catId: draggingNode.data.categoryEntities[index].catId,
        //         name: draggingNode.data.categoryEntities[index].name,
        //         parentCid: draggingNode.data.categoryEntities[index].parentCid,
        //         catLevel: draggingNode.data.categoryEntities[index].catLevel - 1,
        //         sort: index
        //       })
        //     }
        //     console.log('收到的集合', this.updTree)
        //   }
        // } else if (this.level === 1) {
        //   if (dropNode.data.catLevel === 1) {
        //     for (let index = 0; index < dropNode.parent.data.length; index++) {
        //       this.updTree.push({
        //         catId: dropNode.parent.data[index].catId,
        //         name: dropNode.parent.data[index].name,
        //         parentCid: dropNode.data.parentCid,
        //         catLevel: dropNode.data.catLevel,
        //         sort: index
        //       })
        //     }
        //     console.log('收到的集合', this.updTree)
        //   } else {
        //     for (let index = 0; index < dropNode.parent.data.categoryEntities.length; index++) {
        //       this.updTree.push({
        //         catId: dropNode.parent.data.categoryEntities[index].catId,
        //         name: dropNode.parent.data.categoryEntities[index].name,
        //         parentCid: dropNode.data.parentCid,
        //         catLevel: dropNode.data.catLevel,
        //         sort: index
        //       })
        //     }
        //     console.log('收到的集合', this.updTree)
        //   }
        // }